layui.define(["form", "table", "jquery", "layer", "file", "code", "cookies"], function(exports){
    var form = layui.form;
    var table = layui.table;
    var $ = layui.jquery;
    var layer = layui.layer;
    var fileModule = layui.file;
    var cookies  = layui.cookies;
    var x = {};

    function toFormData(data)
    {
        var fd = new FormData();
        for(var key in data){
            fd.append(key, data[key]);
        }
        return fd;
    }

    function arrayUnique(list)
    {
        return Array.from(new Set(list));
    }
    
    x.post = function(url, data, successCallback, failCallback)
    {
        function success(response)
        {
            if(response.ok == true && response.status == 200){
                response.json().then(function(json){
                    successCallback(json);
                });
            }
        }
        
        function fail(response)
        {
            failCallback(response);
        }
        
        fetch(url, {method: "post", body: data}).then(success).catch(fail);
    };

    x.submit = function(verify, indexUrl, handleUrl)
    {
        form.verify(verify);

        form.on('submit(default)', function(data){
            function success(json)
            {
                var callback = function(){};
                if(json.code == 0){
                    callback = function(){
                        if(indexUrl == ''){
                            window.location.reload();
                        }
                        else{
                            window.location.href = indexUrl;
                        }
                    };
                }
                layer.msg(json.msg, callback);
            }

            function fail(response)
            {
                console.log(response);
            }

            x.post(handleUrl, toFormData(data.field), success, fail);
            return false;
        });
    };

    x.list = function(url, cols, limit, f)
    {
        var config = {
            elem: '#list',
            url: url,
            cols: [cols],
            page: true,
            limit: limit,
            limits: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 500, 1000],
            id: "list",
            toolbar: '#toolbar',
            done: f["done"],
            where: {
                "rand": Math.random()
            }
        };

        if(f['search']){
            config.where = f['search']();
        }

        var instance = table.render(config);

        /*全局的操作按钮*/
        table.on('toolbar(list)', function(object){
            f[object.event](object, table.checkStatus(object.config.id));
        });

        /*每条记录的操作按钮*/
        table.on('tool(list)', function(e){
            f[e.event](e, e.data.id);
        });

        /*数据被即时编辑*/
        table.on('edit(list)', function(object){
            f["immediatelyEdit"](object);
        });

        return {
            instance: instance,
            config: config
        };
        /**/
    };

    x.mergeRequest = function()
    {
        function doRequest(role, field, url, iframeUrl, full, value)
        {
            function success(json)
            {
                var string = JSON.stringify(json);
                $(`div.dryMergeRequest[field='${field}']`).each(function(){
                    var that = $(this);
                    var theValue = that.html();
                    if(role == "tag"){
                        that.html(`<textarea style="display:none;">${string}</textarea><dry-common role="tag" value="${theValue}"></dry-common>`);
                    }
                    else if(role == "file"){
                        fileModule.fileShow(that, json, iframeUrl, full, theValue);
                    }
                });
            }
            
            var data = {
                "dataIn": value
            };
            x.post(url, toFormData(data), success, function(){});
        }

        var map = {};
        $("div.dryMergeRequest").each(function(){
            var role = $(this).attr("role");
            var iframeUrl = $(this).attr("iframeUrl");
            var full = $(this).attr("full");
            var field = $(this).attr("field");
            var url = $(this).attr("url");
            var temp = $(this).html().split(",");
            var value = [];
            for(var i in temp){
                if(temp[i]){
                    value.push(temp[i]);
                }
            }
            if(!map[field]){
                map[field] = {
                    "role": "",
                    "iframeUrl": "",
                    "full": "",
                    "url": "",
                    "value": []
                };
            }
            var item = map[field];
            item.role = role;
            item.iframeUrl = iframeUrl;
            item.full = full;
            item.url = url;
            item.value.push(...value);
            item.value = arrayUnique(item.value);
            map[field] = item;
        });

        for(var field in map){
            var item = map[field];
            if(item.value.length){
                doRequest(item.role, field, item.url, item.iframeUrl, item.full, item.value.join(","));
            }
        }
        fileModule.doFileFullShow();
    };

    x.fieldDataSource = function()
    {
        function switchDo(value)
        {
            var list = [
                "#dry_variable",
                "#dry_domain",
                "#dry_api",
                "#dry_model_alias",
                "#dry_key_field",
                "#dry_value_field",
                "#dry_sql",
                "#dry_callback",
                "#dry_data_pool_name"
            ];
            var config = [];
            config[0] = [];
            config[1] = [
                "#dry_variable"
            ];
            config[2] = [
                "#dry_domain",
                "#dry_api"
            ];
            config[3] = [
                "#dry_domain",
                "#dry_api",
                "#dry_model_alias",
                "#dry_key_field",
                "#dry_value_field",
                "#dry_sql",
                "#dry_callback"
            ];
            config[4] = [
                "#dry_data_pool_name"
            ];
            for(var i = 0;i < list.length;i++){
                $(list[i]).parent().parent().parent().hide();
            }
            var showList = config[value];
            for(var i = 0;i < showList.length;i++){
                $(showList[i]).parent().parent().parent().show();
            }
        }
        
        function run()
        {
            form.on("radio(dry_data_source)", function(data){
                switchDo(data.value);
            });
            switchDo($("input[name='dry_data_source']:checked").val());
        }
        
        function isAllOk()
        {
            var length1 = $("form.layui-form").find("dry-common").length;
            var length2 = $("form.layui-form").find("dry-common[ok='1']").length;
            return length1 == length2;
        }
        
        if(isAllOk()){
            run();
        }
        else{
            window.setTimeout(function(){
                x.fieldDataSource();
            }, 20);
        }
    };
    
    /*
        在a函数返回true后才执行b函数
    */
    x.runAfter = function(a, b)
    {
        if(a()){
            b();
        }
        else{
            window.setTimeout(function(){
                x.runAfter(a, b);
            }, 20);
        }
    };
    
    x.call = function()
    {
        $("td.call").each(function(){
            var that = $(this);
            var name = that.attr("name");
            var data = that.attr("data");
            var list = data.split(",");
            var html = window[name].apply(null, list);
            that.html(html);
        });
    };
    
    x.htmlShow = function()
    {
        $(".htmlShow").click(function(){
            var html = $(this).parent().find("textarea").val();
            var content = '<div style="padding:10px;">' + html + '</div>';
            var width = window.innerWidth - 50;
            var height = window.innerHeight - 50;
            layer.open({
                type: 1,
                skin: 'layui-layer-rim',
                area: [width + "px", height + "px"],
                content: content
            });
        });
    };
    
    x.codeShow = function()
    {
        $(".codeShow").click(function(){
            var code = $(this).parent().find("textarea").val();
            var width = window.innerWidth - 50;
            var height = window.innerHeight - 50;
            var content = `<div style="padding:0 10px;"><pre class="layui-code" lay-title="内容" lay-height="${height}" lay-skin="" lay-encode="false">${code}</pre></div>`;
            layer.open({
                type: 1,
                skin: 'layui-layer-rim',
                area: [width + "px", height + "px"],
                content: content
            });
            layui.code({"about": false});
        });
    };
    
    x.fold = function()
    {
        $(".dry-fold").click(function(){
            $(this).parent().find("div.layui-card-body").toggleClass("layui-hide");
        });
    };
    
    x.cardRightTopButton = function(f)
    {
        $(".cardRightTop").click(function(){
            var event = $(this).attr("lay-event");
            f[event]();
        });
    };
    
    x.addEditWidth = function(width)
    {
        if(width == 'none'){
            return false;
        }
        var width = window[width];
        var left = width + 30;
        var css = `
        <style>
            .layui-form-label {
                width: ${width}px;
            }
            .layui-input-block {
                margin-left: ${left}px;
            }
        </style>
        `;
        $("body").append(css);
    };
    
    x.logout = function(logoutUrl, loginUrl)
    {
        function success()
        {
            cookies.removeItem("PHPSESSID", "/");
            cookies.removeItem("group", "/");
            cookies.removeItem("token", "/");
            window.location.href = loginUrl;
        }
        
        var data = {};
        var sessionId = cookies.getItem("PHPSESSID");
        var token = cookies.getItem("token");
        if(sessionId){
            data.sessionId = sessionId;
        }
        if(token){
            data.token = token;
        }
        data.device = "admin";
        x.post(logoutUrl, toFormData(data), success, function(){});
    };
    
    x.isLogin = function(isLoginUrl, loginUrl, span)
    {
        function success(json)
        {
            if(json.code > 0){
                layer.msg(json.msg, function(){
                    window.location.href = loginUrl;
                });
            }
            else{
                window.setTimeout(check, span);
            }
        }
        
        function check()
        {
            var token = cookies.getItem("token");
            if(!token){
                window.location.href = loginUrl;
            }
            else{
                sendGetRequest(isLoginUrl + "?device=admin&token=" + token, success, function(){});
            }
        }
        
       check();
    };

    x.open = function(url, isIframe)
    {
        if(isIframe){
            layer.open({
                type: 2,
                title: "窗口",
                shadeClose: false,
                shade: 0.8,
                area: ['100%', '100%'],
                maxmin: true,
                content: url
            });
        }
        else{
            window.location.href = url;
        }
    };

    x.delete = function(url, idsString)
    {
        function ok()
        {
            function success()
            {
                layer.msg("已删除", function(){
                    window.location.reload();
                });
            }

            x.post(url, toFormData({ids: idsString}), success);
        }

        function cancel()
        {
            layer.msg("已取消");
        }

        if(idsString == ""){
            return false;
        }

        layer.confirm('确定删除吗?', {btn:['确定','取消']}, ok, cancel);
    };

    exports('dry', x);
});